﻿/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
**     the names of its contributors may be used to endorse or promote
**     products derived from this software without specific prior written
**     permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/


#include <QMessageBox>
#include <QLabel>
#include <QFileInfo>
#include <QCoreApplication>
#include <QtSerialPort/QSerialPort>
#include <QApplication>

#include "connection_serial.h"
#include "dialog.h"
#include "linuxcontrol.h"
#include "settingsdialog.h"

CxConnection_serial::CxConnection_serial(Dialog *pdialog):CxConnection(pdialog)
{
    Dialog *apdialog =  CxConnection::getdialog();

    apdialog = pdialog;

    m_igetpackage =0;

    m_igetping = 0;
    m_igetpong = 1;
    m_itype = 0;//1 serial to serial 0 serial to tcpip

    m_isendok = 0;

    //! [1]
    m_serial = new QSerialPort(this);
    //! [1]
    m_settings = new SettingsDialog;

    connect(m_serial, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(&QSerialPort::error),
                this, &CxConnection_serial::handleError);
      //! [2]
    connect(m_serial, &QSerialPort::readyRead, this, &CxConnection_serial::readData_serial);

    connect(&m_retrytimer, SIGNAL(timeout()), this, SLOT(retryrun()));

    m_ihead = 0;

    m_ireadytotransfor = 0;

    m_iprocessover = 0;

    m_icurdealnum = 0;
    m_iclearnum = 0;
    m_ifindhead = -1;
    m_ifindtail = -1;
    m_iarraysize =0;
    m_ifinishsendfile =1;
    m_processeventtimer.start(20,this);
    m_iserialgetdata = 0;
    m_iserialclear = 0;
}
CxConnection_serial::CxConnection_serial(Dialog *pdialog,int icos):CxConnection(pdialog,0)
{
   Dialog *apdialog =  CxConnection::getdialog();

   apdialog = pdialog;

   m_tcpClient = 0;

    m_igetping = 0;
    m_igetpong = 1;
    m_itype = 0;//1 serial to serial 0 serial to tcpip

    m_isendok = 0;
    //! [1]
    m_serial = new QSerialPort(this);
    //! [1]
    m_settings = new SettingsDialog;

    connect(m_serial, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(&QSerialPort::error),
                this, &CxConnection_serial::handleError);
    connect(m_serial, &QSerialPort::readyRead, this, &CxConnection_serial::readData_serial);

    openSerialPort();

    m_ihead = 0;
    m_ireadytotransfor = 0;
    m_iprocessover = 0;

    m_icurdealnum = 0;
m_iclearnum = 0;
    m_ifindhead = -1;
    m_ifindtail = -1;

    m_iarraysize =0;
    m_ifinishsendfile =1;
    m_processeventtimer.start(20,this);
    m_iserialgetdata = 0;
    m_iserialclear = 0;
}
CxConnection_serial::CxConnection_serial(Dialog *pdialog,QTcpSocket *parent):CxConnection(pdialog,parent)
{
    Dialog *apdialog =  CxConnection::getdialog();

    apdialog = pdialog;


    m_serial = 0;

    m_igetping = 0;
    m_igetpong = 1;
    m_itype = 0;//1 serial to serial 0 serial to tcpip

    m_isendok = 0;
    //! [1]
    m_tcpClient = parent;
      //! [2]
      connect(m_tcpClient, SIGNAL(readyRead()), this, SLOT(readData_tcpip()));
      connect(m_tcpClient, SIGNAL(connected()), this, SLOT(startTransfer()));
      connect(m_tcpClient, SIGNAL(disconnected()), this, SLOT(stopTransfer()));

      m_iconnected = 0;

      m_eventtimer.start(2000,this);
      //m_processeventtimer.start(20,this);
      m_bgetdata =false;
      m_icontinuetimes =0;
//      connect(&m_retrytimer, SIGNAL(timeout()), this, SLOT(retryrun()));

      m_ihead = 0;
      m_ireadytotransfor = 0;
      m_iprocessover = 0;

      m_icurdealnum = 0;
      m_ifindhead = -1;
      m_ifindtail = -1;
      m_iarraysize =0;
    m_iclearnum = 0;
    m_ifinishsendfile =1;
    m_iserialgetdata = 0;
    m_iserialclear = 0;
}
CxConnection_serial::~CxConnection_serial()
{
    closeSerialPort();
    if(m_settings)
    delete m_settings;
    if(m_serial)
    delete m_serial;
     //delete ui;
}
void CxConnection_serial::reset()
{
        closeSerialPort();
        openSerialPort();
}
void CxConnection_serial::processRead()
{
   CxConnection::processRead();
}
//! [6]
void CxConnection_serial::writeData(const QByteArray &data)
{

    m_retrydata = data;
    if(m_serial)
    {
        m_serial->write(data);
        return;
    }
    QTcpSocket *psocket =  CxConnection::getsocket();
    if(psocket)
    {
        m_senddata = data;
    }
}
//! [6]
void CxConnection_serial::stopTransfer()
{
    m_iconnected = 0;

}
void CxConnection_serial::startTransfer()
{
    m_iconnected = 1;

}
void CxConnection_serial::parserpackagestring()
{
    int ibeginnum = -1;
    int iendnum = -1;
    int isize = m_iarraysize;
    int ibegin = 0;
    for(int ix=0;ix<isize;ix++)
    {
        if(m_buftype[ix]==2
                &&0==ibegin)
        {
            ibegin =1;
            ibeginnum = ix;
        }
        if(m_buftype[ix]==8)
            iendnum = ix;
    }
    if(-1==ibeginnum
    ||-1==iendnum)
        return;
    QByteArray data;
    ibegin = 0;
    for(int i=ibeginnum;i<=iendnum;i++)
    {
        if(m_buftype[i]==2
          &&0==ibegin)
        {
            ibegin = 1;
            int ih = m_readBuf[i].indexOf("^HEAD",0);
           if(ih>=0)
            data = m_readBuf[i].mid(ih+5);
        }
        else if(m_buftype[i]==8)
        {
            int ied0 = m_readBuf[i].indexOf("@EnD~",0);
            if(ied0>=0)
            {
                data = data +m_readBuf[i].mid(0,ied0+5);
                break;
            }
            else
            {
                if(i+1<isize)
                {
                    QByteArray qbty =  m_readBuf[i]+  m_readBuf[i+1] ;
                    int ied1 = qbty.indexOf("@EnD~",0);

                    if(ied1>=0)
                    {
                        data = data + qbty.mid(0,ied1+5);
                        break;
                    }
                    else
                        data = data + m_readBuf[i];

                }
            }
        }
        else
            data = data + m_readBuf[i];

    }

    QByteArray endsign("@EnD~");
            QByteArray tmpget;
            tmpget[0] = data.at(0);
            tmpget[1] = data.at(1);
            QByteArray tmp  = gemfieldCRC(data.mid(2));//CRC[0]+ CRC[1]+CRC[2]+ CRC[4]

            if(tmpget[0]==tmp[0]
            &&tmpget[1]==tmp[1] )
            {

                qint64 isize = data.size() - endsign.size() - 2;

                QByteArray filehead("FILE ");
                QByteArray filmhead("FILM ");
                QByteArray stringhead("STRING ");
                QByteArray controlhead("CONT ");
                QByteArray desktopimagehead("IMAGE ");
                QByteArray varhead("VALUE ");

                if(data.mid(2,5)==filehead)
                {
                    qint64 ireadsize = isize - 64;
                    QByteArray filename = data.mid(2+5, 59);
                    QByteArray qname = filename.split('~')[0];
                    QByteArray buf3 = qUncompress(data.mid(64+2,ireadsize));
                    getdialog()->savefile(buf3,qname);
                    ShowLog("getfile "+qname);
                    ShowLog(" ");
                    QByteArray Msgsendok("SOK");
                    sendCommand(Msgsendok);
                }
                else if(data.mid(2,6)==desktopimagehead)
                {
                    qint64 ireadsize = isize - 64;
                    QByteArray filename = data.mid(2+5, 59);
                    QByteArray qname = filename.split('~')[0];
                    QString qstrname = qname;
                    QStringList	mslist = qstrname.split("_");

                    int imagew = mslist[0].toInt();
                    int imageh = mslist[1].toInt();
                    QByteArray buf3 = qUncompress(data.mid(64+2,ireadsize));

                    QImage image((uchar*)buf3.data(),imagew,imageh,QImage::Format_RGB16);

                    getdialog()->setimage(image);
                    ShowLog("getimage "+qname);
                    ShowLog(" ");
                    QByteArray Msgsendok("SOK");
                    sendCommand(Msgsendok);
                }
                else if(data.mid(2,6)==varhead)
                {
                    qint64 ireadsize = isize - 64;
                    QByteArray filename = data.mid(2+5, 59);
                    QByteArray qname = filename.split('~')[0];
                    QString qstrname = qname;
                    QStringList	mslist = qstrname.split("_");

                    QString varname = mslist[0];
                    QString varvalue = mslist[1];
                    //getdialog()->setimage(image);
                    getdialog()->SetTextEditText(varname);
                    getdialog()->SetValueEditText(varvalue);
                    getdialog()->SetValue();
                    ShowLog("getvalue "+varname +":"+varvalue);
                    ShowLog(" ");
                    QByteArray Msgsendok("SOK");
                    sendCommand(Msgsendok);

                }
                else if(data.mid(2,7)==stringhead)
                {
                    qint64 ireadsize = isize - 64;
                    QByteArray filename = data.mid(2+7, 59);
                    QByteArray qname = filename.split('~')[0];
                    QString qstrname = qname;
                    ShowLog("getstring "+qstrname);
                    ShowLog(" ");
                    QByteArray Msgsendok("SOK");
                    sendCommand(Msgsendok);

                }
                else if(data.mid(2,5)==controlhead)
                {

                }



            }
            else
            {
                ShowLog("crc error getimage " );
                ShowLog(" ");
                QByteArray Msgsendok("SOK");
                sendCommand(Msgsendok);
               // reset();
            }




        for(int i=ibeginnum;i<=iendnum;i++)
        {
            m_buftype[i] = 0;
        }


}
int CxConnection_serial::ParserArray(QByteArray &strarray,int& ibeginsign,int& iendsign)
{
    char charc = 0;
    strarray.replace(charc,QByteArray(""));

    int index0=0;
    while(index0<strarray.size()-1
          &&index0>=0)
    {
        index0 = strarray.indexOf(QByteArray("cxvisionaiping"),index0);
        if(index0>=0)
        strarray.replace(index0,14,QByteArray(""));
    }

    index0=0;
    while(index0<strarray.size()-1
          &&index0>=0)
    {
        index0 = strarray.indexOf(QByteArray("transfordata"),index0);
        if(index0>=0)
        strarray.replace(index0,12,QByteArray(""));
    }

    index0=0;
    while(index0<strarray.size()-1
          &&index0>=0)
    {
        index0 = strarray.indexOf(QByteArray("state1"),index0);
        if(index0>=0)
        strarray.replace(index0,6,QByteArray(""));
    }
    index0=0;
    while(index0<strarray.size()-1
          &&index0>=0)
    {
        index0 = strarray.indexOf(QByteArray("state0"),index0);
        if(index0>=0)
        strarray.replace(index0,6,QByteArray(""));
    }

    index0=0;
    while(index0<strarray.size()-1
          &&index0>=0)
    {
        index0 = strarray.indexOf(QByteArray("state0\r\n"),index0);
        if(index0>=0)
        strarray.replace(index0,8,QByteArray(""));
    }

    int iresultnum = 0;
    if(strarray=="")
    {
        return 0;
    }
    else
    {
        if(-1==ibeginsign)
        {
            index0 = strarray.indexOf(QByteArray("^HEAD"),0);
            if(index0>=0)
            {
                ibeginsign = index0;
                iresultnum = iresultnum + 2;
            }
        }
        if(-1==ibeginsign)
        {
            index0 = strarray.indexOf(QByteArray("COMM "),0);
            if(index0>=0)
            {
               ibeginsign = index0;
                iresultnum = iresultnum + 4;
            }

        }
        if(-1==iendsign)
        {
            index0 = strarray.indexOf(QByteArray("@EnD~"),0);
            if(index0>=0)
            {
                iendsign = index0;
                iresultnum = iresultnum + 8;
            }

        }
    }
    if(0==iresultnum)
        return 1;
    else
        return iresultnum;
}
void CxConnection_serial::ProcessDataBuffClear_serial()
{
    int isize = m_iarraysize;
    for(int ix=0;ix<isize;ix++)
    {
        m_buftype[ix] = 0;
    }
}
void CxConnection_serial::ProcessDataBuff_serial()
{
        int isize = m_iarraysize;

            for(int ix=0;ix<isize;ix++)
            {
                if(m_buftype[ix]==-1)
                {
                    QByteArray strarray = m_readBuf[ix];

                    int ibeginnum =  -1;
                    int iendnum =  -1;

                    int itype = ParserArray(strarray,ibeginnum,iendnum);
                    m_buftype[ix] = itype;

                    if(ibeginnum!=-1&&m_ifindhead==-1)
                    {
                        m_ifindhead = ibeginnum;
                        m_beginend[ix].setX(ibeginnum);
                        ShowLog("Get<pack begin>");
                    }
                    else if(iendnum!=-1&&m_ifindtail==-1)
                    {
                        m_ifindtail = iendnum;
                        m_beginend[ix].setY(iendnum);
                        ShowLog("Get<pack End>");
                        m_ifindhead = -1;
                        m_ifindtail = -1;
                    }
                    else if(m_ifindhead==-1
                            &&ix>0)
                    {
                        if(m_buftype[ix-1]!=0)
                        {
                            strarray = m_readBuf[ix-1]+m_readBuf[ix];
                             iendnum = -1;
                             ibeginnum = -1;
                            int itype = ParserArray(strarray,ibeginnum,iendnum);
                            if(0==itype)
                            {
                                m_buftype[ix] = 0;
                                m_buftype[ix-1] = 0;
                            }
                            else
                            {
                                if(ibeginnum!=-1)
                                {
                                    m_ifindhead = ibeginnum;
                                    m_beginend[ix].setX(ibeginnum);
                                    ShowLog("Get<pack begin>");

                                }
                            }
                        }
                    }
                    else if(m_ifindhead>=0
                     &&m_ifindtail==-1
                     &&ix>0)
                    {
                        if(m_buftype[ix-1]!=0)
                        {
                            iendnum = -1;
                            strarray = m_readBuf[ix-1]+m_readBuf[ix];
                            int itype = ParserArray(strarray,ibeginnum,iendnum);

                            if(iendnum!=-1&&m_ifindtail==-1)
                            {
                                m_ifindtail = iendnum;
                                m_beginend[ix].setY(iendnum);
                                ShowLog("Get<pack End>");
                            }
                            m_buftype[ix] = itype;
                            m_buftype[ix-1] = itype;

                        }
                    }
                }
                else
                {
                    if(ix>0)
                    {
                        if(m_buftype[ix]!=2
                          &&m_buftype[ix]!=4
                          &&m_buftype[ix-1]!=2
                          &&m_buftype[ix-1]!=4
                          &&m_buftype[ix-1]!=16
                          &&m_buftype[ix]!=0
                          &&m_buftype[ix-1]!=0)
                        {
                            QByteArray strarray = m_readBuf[ix-1]+m_readBuf[ix];

                            int ibeginnum =  -1;
                            int iendnum =  -1;

                            int itype = ParserArray(strarray,ibeginnum,iendnum);
                            if(itype==0)
                            {
                                m_buftype[ix] = 0;
                                m_buftype[ix-1] = 0;

                            }
                            else
                            {

                                m_buftype[ix-1] = 16;
                                if(iendnum!=-1&&m_ifindtail==-1)
                                {
                                    m_buftype[ix] = 8;
                                    m_ifindtail = iendnum;
                                    m_beginend[ix].setY(iendnum);
                                    ShowLog("Get<pack End>");
                                    m_ifindtail = -1 ;
                                    m_ifindhead = -1 ;
                                }
                                else if(ibeginnum!=-1&&m_ifindhead==-1)
                                {
                                    m_buftype[ix] = 2;
                                    m_ifindhead = ibeginnum;
                                    m_beginend[ix-1].setX(ibeginnum);
                                    ShowLog("Get<pack Begin>");
                                }

                            }
                        }
                    }
                }
            }


}
void CxConnection_serial::readData_tcpip()
{
         QByteArray data ;
         if(m_serial)
            data = m_serial->readAll();
         else
         {
            QTcpSocket *psocket =  CxConnection::getsocket();
            if(psocket)
            {
                data = psocket->readAll();
            }
         }

        QByteArray headdata1 = data.mid(0,14);
        while(headdata1==QByteArray("cxvisionaiping"))//com
        {
            getdialog()->setwintext(QTime::currentTime().toString("hh:mm:ss ")+"cxvisionaiping");
            data = data.mid(14);
            headdata1 = data.mid(0,14);
            m_igetping = 1;
            m_igetpackage = 0;
        }
        QByteArray headdata2 = data.mid(0,12);
        while(headdata2==QByteArray("cxvisionpong"))//ip
        {
            getdialog()->setwintext(QTime::currentTime().toString("hh:mm:ss ")+"cxvisionpong");
            data = data.mid(12);
            headdata2 = data.mid(0,12);
            m_igetpong = 1;
            m_igetpackage = 0;
        }

        QByteArray headdata3 = data.mid(0,12);
        if(headdata3==QByteArray("transfordata"))//ip
        {
            getdialog()->setwintext(QTime::currentTime().toString("hh:mm:ss ")+"transfordata");
            data = data.mid(12);

            m_igetpong = 1;
            m_igetpackage = 0;
        }
        QByteArray headdata4 = data.mid(0,6);
        if(headdata4==QByteArray("state1"))//ip
        {
             ShowLog("state1");
             ShowLog("");
            data = data.mid(6);
            m_igetpong = 1;
            m_igetpackage = 0;
        }
        QByteArray headdata5 = data.mid(0,6);
        if(headdata5==QByteArray("state0"))//ip
        {
             ShowLog("state0");
             ShowLog("");
            data = data.mid(6);
            m_igetpong = 1;
            m_igetpackage = 0;
        }

         if(data=="")
            return;

        m_bgetdata = true;
        QByteArray endsign =  QByteArray("@EnD~");
        QByteArray headsign = QByteArray("^HEAD");
        bool bhead = data.contains(headsign);
        bool bend = data.contains(endsign);

        if(0==m_ihead)
        {
            if(true ==bhead)
            {
                m_ihead = 1;
                int ih = data.indexOf(headsign,0);
                data = data.mid(ih+5);

            }
        }

        if(0==m_ihead)
        {
            bool gethead =m_readData.contains(headsign);
            if(false ==gethead)
                m_readData.clear();
            else
            {
               int ih = m_readData.indexOf(headsign,0);
               m_readData = m_readData.mid(ih+5);
            }

        }
        m_igetpackage = m_igetpackage + 1;
        QString strpackage = tr("getpack %1 ").arg(m_igetpackage);

        SetLog(strpackage);

        if(false==bend)
        {
             m_readData.append(data);
            if(data.contains("~"))
            {

                 bend = m_readData.contains(endsign);
                 if(true ==bend)
                 {
                     int ied = m_readData.indexOf("@EnD~",0);
                    m_readData = m_readData.mid(0,ied+5);
                     m_ihead = 0;
                 }
                 else
                {
                     return;
                 }
            }
            else
            {

                return;
            }
        }
        else
        {
            int ied0 = data.indexOf("@EnD~",0);
            data = data.mid(0,ied0+5);
            m_readData.append(data);
        }
        //AddLog(".");



            if(m_readData.right(5)==endsign)
            {
                m_ihead = 0;
                bend = false;
                QByteArray msghead("COMM ");

                if(m_readData.mid(0,5)==msghead)
                {
                    QByteArray Msgsendok("SOK");
                    if(m_readData.mid(5,3)==Msgsendok)
                    {
                        m_isendok = 1;
                        m_ireadytotransfor = 0;
                        m_ifinishsendfile = 1;
                        m_igetpong = 1;

                    }
                    QByteArray Msgsretry("SRETRY");
                    if(m_readData.mid(5,6)==Msgsretry)
                    {
                        m_ireadytotransfor = 0;
                        m_ifinishsendfile = 1;
                        m_igetpong = 1;

                        //writeData(m_retrydata);
                    }
                    QByteArray Msgready("Ready");
                    if(m_readData.mid(5,5)==Msgready)
                    {
                        m_ireadytotransfor = 1;

                        //writeData(m_retrydata);
                    }
                    QByteArray MsgA("A");
                    if(m_readData.mid(5,1)==MsgA)
                    {
                        senddesktopimage();
                     }
                    QByteArray MsgB("B");
                    if(m_readData.mid(5,1)==MsgB)
                    {
                        int iparm1 = m_readData.mid(6,4).toInt();
                        iparm1 ;
                        QByteArray getbytearray = m_readData.mid(0,m_readData.size()-5);
                        getbytearray = getbytearray.mid(6);
                        getdialog()->SetCodeText(getbytearray);
                        getdialog()->TestParser();
                    }
                    QByteArray MsgC("C");
                    if(m_readData.mid(5,1)==MsgC)
                    {

                    }
                    ShowLog(m_readData );
                    ShowLog("");
                     m_readData.clear();
                     return;
                }


                QByteArray tmpget;
                tmpget[0] = m_readData.at(0);

                tmpget[1] = m_readData.at(1);
                QByteArray tmp  = gemfieldCRC(m_readData.mid(2));//CRC[0]+ CRC[1]+CRC[2]+ CRC[4]

                if(tmpget[0]==tmp[0]
                &&tmpget[1]==tmp[1] )
                {
                    qint64 isize = m_readData.size() - endsign.size() - 2;

                    QByteArray msghead("COMM ");
                    QByteArray filehead("FILE ");
                    QByteArray filxhead("FILX ");//>1M file and <100 M
                    QByteArray filmhead("FILM ");
                    QByteArray controlhead("CONT ");

                    if(m_readData.mid(2,5)==msghead)
                    {
                        qint64 ireadsize = isize - msghead.size();
                        QByteArray Msgsendok("SOK");
                        if(m_readData.mid(7,3)==Msgsendok)
                        {
                            m_isendok = 1;
                            m_ireadytotransfor = 0;
                        }
                        QByteArray Msgsretry("SRETRY");
                        if(m_readData.mid(7,6)==Msgsretry)
                        {
                            m_ireadytotransfor = 0;
                            //writeData(m_retrydata);
                        }

                        QByteArray MsgA("A");
                        if(m_readData.mid(7,1)==MsgA)
                        {
                            ShowLog("finish send");
                            ShowLog("");
                        }
                        //ShowLog(m_readData.mid(7,ireadsize));
                        //ShowLog("");
                    }
                    else if(m_readData.mid(2,5)==filehead)
                    {
                        qint64 ireadsize = isize - 64;
                        QByteArray filename = m_readData.mid(2+5, 59);
                        QByteArray qname = filename.split('~')[0];

                        QByteArray buf3 = qUncompress(m_readData.mid(64+2,ireadsize));
                        getdialog()->savefile(buf3,qname);
                        ShowLog("getfile "+qname);
                        ShowLog(" ");
                        QByteArray Msgsendok("SOK");
                        sendCommand(Msgsendok);
                    }
                    else if(m_readData.mid(2,5)==filxhead)
                    {

                        qint64 ireadsize = isize - 64;
                        QByteArray filename = m_readData.mid(2+5,59);
                        QByteArray qname = filename.split('~')[0];
                        QByteArray qsplitnum("0");
                        QByteArray qtotalnum("0");
                        if(filename.split('~').size()>2)
                            qsplitnum = filename.split('~')[1];
                        if(filename.split('~').size()>3)
                            qtotalnum = filename.split('~')[2];
                        qint64 isplitnum = qsplitnum.toInt();
                        qint64 itotalnum = qtotalnum.toInt();

                        m_filelist[isplitnum] = m_readData.mid(64+2,ireadsize);
                        ShowLog("getfile "+qname+qtotalnum + "\\" +qsplitnum);

                        QByteArray bufall;
                        if(isplitnum>=itotalnum-1)
                        {
                            for(int i=0;i<itotalnum;i++)
                                bufall =bufall + m_filelist[i];
                            QByteArray buf3 =  qUncompress(bufall);
                             getdialog()->savefile(buf3,qname );
                             ShowLog("finishfile "+qname);

                             QByteArray Msgsendok("SOK");
                             sendCommand(Msgsendok);
                             ShowLog("");
                        }
                        //m_isretry = 0;
                    }
                    else if(m_readData.mid(2,5)==filmhead)
                    {
                    }
                    if(m_readData.mid(2,5)==controlhead)
                    {

                        qint64 ireadsize = isize - controlhead.size();
                        getdialog()->setEditText(m_readData.mid(7));
                        getdialog()->sendCommand();

                        ShowLog("CONTROL "+m_readData.mid(7));

                    }



                }
                else
                {
                    ShowLog("crc error");
                    QByteArray Msgsretry("SRETRY");
                    sendCommand(Msgsretry);

                }

                m_readData.clear();
            }


}
void CxConnection_serial::readData_serial()
{
         QByteArray data ;
         if(m_serial)
            data = m_serial->readAll();
         else
         {
            QTcpSocket *psocket =  CxConnection::getsocket();
            if(psocket)
            {
                data = psocket->readAll();
            }
         }

         m_iserialgetdata = 1;
         m_readBuf.push_back(data);
         m_iarraysize = m_readBuf.size();
         m_buftype.push_back(-1);
         m_beginend.push_back(QPoint(-1,-1));

         if(0==m_iprocessover)
        {
             m_iprocessover = 1;

            int iz = 0;
            while(iz<m_buftype.size())
            {
                if(0==m_buftype[iz])
                {
                    m_readBuf.remove(iz);
                    m_buftype.remove(iz);
                    m_beginend.remove(iz);
                }
                else
                {
                    iz = iz + 1;
                }
            }


            m_iarraysize = m_readBuf.size();

            m_iprocessover = 0;
        }

         return;

}
void CxConnection_serial::packagedata(const QByteArray &data)
{
   QByteArray enddata = data + QByteArray("@EnD~");

   QByteArray crcdata = gemfieldCRC(enddata);

   QByteArray headdata = QByteArray("^HEAD");
   setbufx(headdata+ crcdata  + enddata);

}
bool CxConnection_serial::sendCommand(const QString &message,const QString &stid)
{
    if (message.isEmpty())
        return false;

    m_iserialclear = 1;
    QByteArray msg = QByteArray("COMM ") + QByteArray(message.toStdString().c_str())  + QByteArray(" @EnD~") ;

    setbufx(msg);

    writeData(getbufx());

    return true;
}
void CxConnection_serial::visionaireq(QByteArray &strarray)
{

}
void CxConnection_serial::sendimage(QImage &aimage)
{
    QByteArray filehead;
    QSize asize = aimage.size();
    QString strsize= QString("%1_%2").arg(asize.width()).arg(asize.height());
    filehead = QByteArray("IMAGE ")+QByteArray(strsize.toStdString().c_str());
    int ifillsize = 64 - filehead.size();
    QByteArray fillstr("~",ifillsize);
    fillstr.fill('~');
    filehead = filehead + fillstr;

    QImage image = aimage.convertToFormat(QImage::Format_RGB16);

    QByteArray imagebits((char*)image.bits(),image.byteCount());

    QByteArray buf3 = qCompress(imagebits);// pdialog->loadfilestring(fileName);//

    setbufx(filehead+buf3);

    packagedata(getbufx());

    writeData(getbufx());

    ShowLog("send image " );

}
void CxConnection_serial::sendvalue(QString &astrname,QString &strvalue)
{
    QByteArray filehead;
     QString strs= astrname + QString("_") +strvalue;
    filehead = QByteArray("VALUE ")+QByteArray(strs.toStdString().c_str());
    int ifillsize = 64 - filehead.size();
    QByteArray fillstr("~",ifillsize);
    fillstr.fill('~');
    filehead = filehead + fillstr;

///    QImage image = aimage.convertToFormat(QImage::Format_RGB16);

//    QByteArray imagebits((char*)image.bits(),image.byteCount());

//    QByteArray buf3 = qCompress(imagebits);// pdialog->loadfilestring(fileName);//

    setbufx(filehead);

    packagedata(getbufx());

    writeData(getbufx());

    ShowLog("send value " + astrname + ":" + strvalue);

}
void CxConnection_serial::sendstring(QString &astring)
{
    QByteArray filehead;
    filehead = QByteArray("STRING ")+QByteArray(astring.toStdString().c_str());
    int ifillsize = 64 - filehead.size();
    QByteArray fillstr("~",ifillsize);
    fillstr.fill('~');
    filehead = filehead + fillstr;

    setbufx(filehead);

    packagedata(getbufx());

    writeData(getbufx());

    ShowLog("send string " + astring);


}
bool CxConnection_serial::senddesktopimage()
{
    return true;
}
void CxConnection_serial::senddir(const QString &fileName)
{
   // QFileInfo afileinf(fileName);
    QDir cxDir(fileName);

    QStringList filelist = cxDir.entryList(QDir::AllEntries, QDir::Name);
    for(int i=0;i<filelist.size();i++)
    {
        if(filelist[i]!="."&&
           filelist[i]!="..")
        {
                 while(0==m_ifinishsendfile)
                   QCoreApplication::processEvents();

                for(int i=0;i<300;i++)
                    QCoreApplication::processEvents();

                m_ifinishsendfile = 0;
                sendfile(fileName +"/" +filelist[i]);


        }
    }

}
bool CxConnection_serial::sendfile(const QString &fileName)
{
    if (fileName.isEmpty())
        return false;

    QByteArray filehead;
    QFileInfo fi(fileName);

    filehead = QByteArray("FILE ")+QByteArray(fi.fileName().toStdString().c_str());
    int ifillsize = 64 - filehead.size();
    QByteArray fillstr("~",ifillsize);
    fillstr.fill('~');
    filehead = filehead + fillstr;
    Dialog* pdialog = getdialog();
    QByteArray buf3 = qCompress(pdialog->loadfilestring(fileName));// pdialog->loadfilestring(fileName);//
    setbufx(filehead+buf3) ;
    packagedata(getbufx());

    writeData(getbufx());

    ShowLog("send file "+fi.fileName());
    return true;
}
bool CxConnection_serial::sendfilex(const QString &fileName)
{
    if (fileName.isEmpty())
        return false;

    QByteArray filehead;
    QFileInfo fi(fileName);
    qint64 isplitnum = 0;
    qint64 itotalnum = 0;
    qint64 ipakage =  1024 * 1   ;
    qint64 ilastnum = 0;

    filehead = QByteArray("FILX ")+QByteArray(fi.fileName().toStdString().c_str());

    QByteArray buf3 =  qCompress(getdialog()->loadfilestring(fileName));

    itotalnum = buf3.size();
    ilastnum =  itotalnum % ipakage ;
    isplitnum = (itotalnum / ipakage) +(ilastnum>0?1:0) ;


    for(qint64 i=0;i<isplitnum;i++)
    {
        QString strnum(tr("~%1~%2").arg(i).arg(isplitnum));
        QByteArray ispnum(strnum.toStdString().c_str());

        int isendnum = 0;
        int ibeginnum = i*ipakage;
        if(i<isplitnum-1)
        {
            isendnum = ipakage ;
        }
        else
        {
            isendnum = ilastnum;
        }

        QByteArray fileheadcur = filehead + ispnum;
        int ifillsize = 64 - fileheadcur.size();
        QByteArray fillstr("~",ifillsize);
        fillstr.fill('~');
        fileheadcur = fileheadcur + fillstr;

        setbufx(fileheadcur+buf3.mid(ibeginnum,isendnum)) ;
        packagedata(getbufx());
        writeData(getbufx());
        ShowLog("send file "+fi.fileName() + ispnum);
        m_isendok = 0;
        while(0==m_isendok)
           QCoreApplication::processEvents();
    }



}
//! [8]
void CxConnection_serial::handleError(QSerialPort::SerialPortError error)
{
    if (error == QSerialPort::ResourceError) {
        ShowLog(tr("Critical Error:")+m_serial->errorString());
        closeSerialPort();
    }
}

//! [4]
void CxConnection_serial::openSerialPort()
{
    SettingsDialog::Settings p = m_settings->settings();
    m_serial->setPortName(p.name);
    m_serial->setBaudRate(p.baudRate);
    m_serial->setDataBits(p.dataBits);
    m_serial->setParity(p.parity);
    m_serial->setStopBits(p.stopBits);
    m_serial->setFlowControl(p.flowControl);
    if (m_serial->open(QIODevice::ReadWrite)) {
        //console->setEnabled(true);
        //console->setLocalEchoEnabled(p.localEchoEnabled);
        //ui->actionConnect->setEnabled(false);
        //ui->actionDisconnect->setEnabled(true);
        //ui->actionConfigure->setEnabled(false);
        ShowLog(tr("Connected to %1 : %2, %3, %4, %5, %6")
                          .arg(p.name).arg(p.stringBaudRate).arg(p.stringDataBits)
                          .arg(p.stringParity).arg(p.stringStopBits)
                          .arg(p.stringFlowControl));
        //connectisok();
        connectstart();
        m_retrytimer.setInterval(4 * 1000);
        m_retrytimer.start();

    } else {
        ShowLog(tr("Error")+ m_serial->errorString());

        ShowLog(tr("Open error"));
    }
}
//! [4]

//! [5]
void CxConnection_serial::closeSerialPort()
{
    if (m_serial->isOpen())
        m_serial->close();
    //console->setEnabled(false);
    //ui->actionConnect->setEnabled(true);
    //ui->actionDisconnect->setEnabled(false);
    //ui->actionConfigure->setEnabled(true);
    //showStatusMessage(tr("Disconnected"));
}
//! [5]

QString CxConnection_serial::getio_local_address_string()
{
  return  QString("0.0.0.0");//m_psocket->localAddress().toString();
}
QString CxConnection_serial::getio_peer_address_string()
{
    return QString("0.0.0.0");//  m_psocket->peerAddress().toString();

}
bool CxConnection_serial::iovalid()
{
    return m_serial->isOpen();//m_psocket->isValid();
}
void CxConnection_serial::ioclose()
{
   closeSerialPort();// m_psocket->close();
}
qint64  CxConnection_serial::iowrite(const QByteArray &data)
{
    return m_serial->write(data);// m_psocket->write(data);
}
QByteArray  CxConnection_serial::EreadAll()
{
    return ioreadall();
}
QByteArray  CxConnection_serial::ioreadall()
{
    QByteArray readData = m_serial->readAll();

    while ( m_serial->waitForReadyRead(500))
        readData.append(m_serial->readAll());
    return readData;
}
QByteArray  CxConnection_serial::ioread(qint64 maxlen)
{
    //return m_serial->readAll();//m_psocket->read(maxlen);
    //return m_serial->read(maxlen);//m_psocket->read(maxlen);

    int ireadsize = 0 ;
    int ineedreadsize =0;
    QByteArray readData = m_serial->read(maxlen);
    ireadsize = readData.size();
    while (ireadsize<maxlen)
    {
        ineedreadsize = maxlen - ireadsize;
        if(m_serial->waitForReadyRead(500))
        {
            readData.append(m_serial->read(ineedreadsize));
            ireadsize =ireadsize + readData.size();
        }
    }
   // while ( m_serial->waitForReadyRead(500))
   //     readData.append(m_serial->readAll());

    return readData;
}
int  CxConnection_serial::iolocalport()
{
    return 0;//m_psocket->localPort();
}
int  CxConnection_serial::iopeerport()
{
    return 0;//m_psocket->peerPort();
}
void  CxConnection_serial::ioabort()
{
   m_serial->clear();// m_psocket->abort();
}
qint64  CxConnection_serial::iobytesAvailable()
{
    return m_serial->bytesAvailable();//m_psocket->bytesAvailable();
}
void CxConnection_serial::overconnect()
{
    m_serial->clear();
 //   m_iuserclass = 0;
 //   pingTimer.stop();
 //   m_dutytimer.stop();
 //   ioclose();
 //   m_pdialog->removeconnect(this);
 //   ShowLog("DisConnect");
  //  if(m_cos==0)
 //       m_reconnectTimer.start();

}
void  CxConnection_serial::retryrun()
{
//    m_reconnectTimer.stop();
    if(!m_serial->isOpen())
    {
        getdialog()->removeconnect(this);
        ShowLog("serial diconnect ");
        openSerialPort();

    }
    /* if(0)
     {
        {

            const int Timeout = 10 * 1000;

            if (!ptcpClient->waitForConnected(Timeout))
            {
                overconnect();
                ShowLog(tr("retry No Connected"));
                m_irestarttimes  = m_irestarttimes  + 1;

                if(m_irestarttimes>30)
                {

                }
                return;
            }
            else
                 connectisok();
            m_pdialog->ReFlashUSER();
        }
    }*/

}
void CxConnection_serial::transforstart()
{
    m_senddata = "transfordata";
}
void CxConnection_serial::sendData()
{
    if(!m_tcpClient)
        return;
   if(0==m_iconnected)
   {
       m_tcpClient->connectToHost(QHostAddress(QString("192.168.1.8")),82);
       const int Timeout = 10 * 1000;
       if (!m_tcpClient->waitForConnected(Timeout))
       {
           return;
       }
   }

   if(m_senddata.isEmpty())
   {
       if(1==m_igetpong)
       {
        QByteArray qba = "cxvisionaiping";
        char a = 0;
        for(int ij=qba.size();ij<700;ij++)
            qba.append(a);

        int  bytesToWrite = (int)m_tcpClient->write(qba);

       }
   }
   else
   {

       if(0==m_ireadytotransfor
        ||m_senddata=="transfordata")
       {
           int isendsize = m_senddata.size()/700;
           int ilastsize = m_senddata.size()%700;
           if(ilastsize>0)
               isendsize = isendsize +1 ;

           QByteArray qba = "transfordata";
          QString qay = tr("%1").arg(isendsize);
           qba = qba + QByteArray(qay.toStdString().c_str());

           char a = 0;

           for(int ij=qba.size();ij<700;ij++)
               qba.append(a);

           int  bytesToWrite = (int)m_tcpClient->write(qba);

            if("transfordata"==m_senddata)
                m_senddata.clear();
       }
       else if(1==m_ireadytotransfor)

       {
           int ilastsize = m_senddata.size()%700;
           char a = 0;
           for(int ij=ilastsize;ij<700;ij++)
               m_senddata.append(a);

           int  bytesToWrite = (int)m_tcpClient->write(m_senddata);
           m_senddata.clear();
       }
   }
}
void CxConnection_serial::timerEvent(QTimerEvent *event)
{
    if(event->timerId() == m_eventtimer.timerId())
    {
        sendData();
    }
    else if(event->timerId() == m_processeventtimer.timerId())
    {
        if(0==m_iprocessover)
        {
           m_iprocessover = 1;
           if(m_iserialclear==1)
           {
               m_iserialclear = 0;
               ProcessDataBuffClear_serial();
           }
           if(m_iserialgetdata==1)
           {
               m_iserialgetdata = 0;

               getdialog()->setwintext(QTime::currentTime().toString("hh:mm:ss ")+"serial getdata");
           }
           ProcessDataBuff_serial();
           parserpackagestring();
        }
        m_iprocessover=0;
    }
}
